CommonUtils.regNamespace("com.im.userManage");

com.im.userManage.invoke = function() {
	var param = {"pageInfo":{"pageSize":20,"pageNumber":1},"statusCd" : '10'};
	var orgparam = {};
    var client = new com.im.common.ajax();
    var operType = "";
    var statusCd = '10';
    var staffDto;//操作员工对象
    var hasList;//员工操作角色
    var allList;//所有的角色
    var staffLimitTypes;//员工权限类型列表
    var ifHasAllLogined;
    var ifHasAll;
    var entry = new Object();
    var orgTypes;
    var rolecolumns=[[
        {field:'name',title:"角色名称",width:100,fitColumns:true},
        {field:'description',title:"角色描述",width:130,fitColumns:true},
        {field:'createDt',title:"创建时间",width:100,fitColumns:true},
        {field:'roleId',title:"角色",width:100,fitColumns:true,hidden:true},
        {field:'statusName',title:"授权操作",width:100,
            formatter: function(value,row,index){
                //员工是否包含
                var hasOper = false;
                $.each(hasList,function(i,obj){

                    if(obj.roleId == row.roleId){
                        hasOper = true;
                        return;
                    }
                });
                if(hasOper){
                    return  '已授权<a href="javascript:;"  onclick="com.im.userManage.invoke.modifyStaff2Roles(\''+index+'\',\'del\')">收回</a>';
                }else{
                    return  '未授权<a href="javascript:;"  onclick="com.im.userManage.invoke.modifyStaff2Roles(\''+index+'\',\'add\')">授权</a>';
                }
            }}
    ]];
    var orgcolumns=[[
        {field:'orgId',title:"序号",fitColumns:true,
            formatter: function(value,row,index){
                return  '<input type="radio" name="r1" class="minimal" value='+index+'></input>';
            }},
        {field:'orgName',title:"单位名称",fitColumns:true},
        {field:'orgType',title:"单位类型",fitColumns:true,
            formatter: function(value,row,index){
                var orgTypeName = '未定义';
                $.each(orgTypes,function(i,obj){
                    if(obj.id == value){
                        orgTypeName = obj.text;
                        return false;
                    }
                });
                return orgTypeName ;
            }},
        {field:'orgAddr',title:"单位地址",fitColumns:true},
        {field:'statusName',title:"状态"}
    ]];

    function _init() {

        _initFunc();
        //初始化加载首页
        _doSearchPage(1,param);
        //查询按钮
        $("#searchUserBtn").click(function(){
            //置空
            var staffName = $("#searchUserTxt").val();
            param.staffName = staffName;
            _doSearchPage(1,param);
        });
        //新增弹出按钮
        $("#toAddUserBtn").click(function(){
            operType =  "add";
            $("#myModalLabel12").html("增加用户");
            $("#userAddEditModal").modal("show");
            _showStaff(null);
        });

        //增加修改
        $("#userInfoBtn").click(function(){
            _addOrUpdateInfo('staff');
        });

        //直接调用show看动态加载模态框不能显示出来
        $('#roleChoseModal').on('shown.bs.modal', function () {
            $("#roleInfoList").empty();
            _showStaffRole(staffDto.staffId);
        });

        //初始化组织树
        $("#jobTree").unitCommpent({
            elmId : "jobTree",//组织树显示的<ul>元素id
            elmIdOut : null,//组织树单击之后回填的文本框（input）
            hasOrgType : true,//组织树是否先展示组织类型
            treeOnClick: function (orgId, orgName) {//组织树单击之后回调函数
                param.orgId = orgId;
                _doSearchPage(1,param);
            }
        });
        //直接调用show看动态加载模态框不能显示出来
        $('#unitSearchModal').on('shown.bs.modal', function () {
            // $("#orgListTb").empty();
            // orgparam.forOrgList = 'Y';
            // //初始化组织类型
            // _initOrgType();
            // //查询
            // _showOrgList(1,orgparam);
            // //初始化组织树
            // $("#unitSearchTree").unitCommpent({
            //     elmId : "unitSearchTree",//组织树显示的<ul>元素id
            //     elmIdOut : null,//组织树单击之后回填的文本框（input）
            //     hasOrgType : true,//组织树是否先展示组织类型
            //     treeOnClick: function (orgId, orgName) {//组织树单击之后回调函数
            //         orgparam.orgId = orgId;
            //         _showOrgList(1)
            //     }
            // });
            // //获取组织树的根节点作为组织类型
            $("#unitOut").unitSearchCommpent({
                elmIdOut : "orgId",//组织树单击之后回填的文本框（input）
                elmIdModal : "unitSearchModal1",
                hasOrgType: true,//组织树是否先展示组织类型
                callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
                    orgparam.orgId = orgId;
                    _showOrgList(1)
                }
            });
        });

        //初始化组织查询按钮
        $("#searchOrgBtn").click(function(){
            operType = 'query';
            $("#unitSearchModal").modal("show");
        });
        //弹出框查询组织按钮
        $("#searchOrgBtnChi").click(function(){
            orgparam.orgType = $("#selectOrgType").val();
            orgparam.orgName = $("#searchOrgName").val();
            _showOrgList(1);
        });
        //弹出框组织确认
        $("#orgEnsureBtn").click(function(){
            var orgIdx = $("input[name='r1']:checked").val();
            if(orgIdx != undefined){
                var org = $('#orgListTb').datagrid('getData').rows[orgIdx];
                if(operType == 'query'){
                    $("#exampleInputName2").val(org.orgName);
                    $("#exampleInputName2").prop("orgId",org.orgId);
                }else{
                    $("#orgId").val(org.orgName);
                    $("#orgId").prop("orgId",org.orgId);
                }
                param.orgId = org.orgId;
                _doSearchPage(1,param);
            }
            $("#unitSearchModal").modal("hide");
        });
        //权限提交
        $("#limitSaveBtn").click(function () {
            _saveOrUpdateLimit();
        });

        //批量删除
        $("#batchDelBtn").click(function () {
            _batchUpdateStaff('batchdel');
        });

        //初始化组织组件
        $("#searchUserBtn").unittypeToSelCommpent({
            elmIdTypeSel : "unitTypeSel",//需要展示的位置下拉框
            elmIdSel : "unitSel",//需要展示的位置下拉框
            callbackFunc: function (objvalue, objname) {//下拉框值改变时回调
                param.orgId = objvalue;
                param.orgType =  $("#unitTypeSel option:selected").attr("value");
                _doSearchPage(1,param);
                //用户管理增加用户界面，如果用户管理界面有选择单位，则新增用户时默认单位为该单位，没有就置空
                $("#orgId").prop('orgId',objvalue);
                $("#orgId").val(objname);
            }
        });
        //查询组织
        $("#unitsearchBtn").click(function () {
            $("#unitOut").unitSearchCommpent({
                elmIdOut : "orgId",//组织树单击之后回填的文本框（input）
                elmIdModal : "unitSearchModal1",
                hasOrgType: true,//组织树是否先展示组织类型
                callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
                    $("#orgId").val(orgName);
                    $("#orgId").prop("orgId",orgId);
                }
            });
        });

        //用户状态
        $('#statusCdTxt').switchbutton({
            checked: true,
            onChange: function(checked){
                if (checked == true){
                    statusCd = '10';
                    param.statusCd = statusCd;
                    _doSearchPage(1,param);
                }
                if (checked == false) {
                    statusCd = '20';
                    param.statusCd = statusCd;
                    _doSearchPage(1,param);
                }}
        });
        //初始化表单验证
        _initFormValid();
    };

    function _initFormValid(){
        $("#userInfoForm").bootstrapValidator({
            live: 'enabled',
            excluded: [':hidden'],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                staffName : {validators: {notEmpty: {message: "请填写用户名称."}}}
                ,staffCode : {validators: {notEmpty: {message: "请填写登录账号."},
                        regexp: {
                            regexp: /^[a-zA-Z0-9]+$/,
                            message: '账号只能由字母、数字组成~'
                        }}}
                ,passWord : {validators: {notEmpty: {
                            message: '密码不能为空'
                        },
                        stringLength: {
                            min: 6,
                            max: 15,
                            message: '密码必须在6-15个字符之间~'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9]+$/,
                            message: '密码只能由字母、数字组成~'
                        }}}
                ,mobileNum : {validators: {notEmpty: {message: "请填写手机号码."},
                        regexp: {
                            regexp: /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                            message: '手机号码格式有误.'
                        }}}
                //,linkTel : {validators: {notEmpty: {message: "请填写联系电话."}}}
                //,email : {validators: {notEmpty: {message: "请填写邮箱地址."},emailAddress: {message: "邮箱格式有误."}}}
                ,orgId : {validators: {notEmpty: {message: "请选择所属组织."}}}
            }
        });
    };
    //修改的时候不要校验密码
    function _initFormValidMod(){
        $("#userInfoForm").bootstrapValidator({
            live: 'enabled',
            excluded: [':hidden'],
            feedbackIcons: {valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-loadData'},
            fields: {
                staffName : {validators: {notEmpty: {message: "请填写用户名称."}}}
                ,staffCode : {validators: {notEmpty: {message: "请填写登录账号."},
                        regexp: {
                            regexp: /^[a-zA-Z0-9]+$/,
                            message: '账号只能由字母、数字组成~'
                        }}}
                // ,passWord : {validators: {notEmpty: {
                //             message: '密码不能为空'
                //         },
                //         stringLength: {
                //             min: 8,
                //             max: 15,
                //             message: '密码必须在8-15个字符之间~'
                //         },
                //         regexp: {
                //             regexp: /^[a-zA-Z0-9]+$/,
                //             message: '密码只能由字母、数字组成~'
                //         }}}
                ,mobileNum : {validators: {notEmpty: {message: "请填写手机号码."},
                        regexp: {
                            regexp: /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/,
                            message: '手机号码格式有误.'
                        }}}
                //,linkTel : {validators: {notEmpty: {message: "请填写联系电话."}}}
                //,email : {validators: {notEmpty: {message: "请填写邮箱地址."},emailAddress: {message: "邮箱格式有误."}}}
                ,orgId : {validators: {notEmpty: {message: "请选择所属组织."}}}
            }
        });
    };
    function _initOrgType(){
        if(orgTypes == undefined){
            var result = client.callAsJson("userService/queryOrgarizationsByCond", { "hasOrgType":'Y'});
            if(result.success){
                orgTypes = result.result;
                $("#selectOrgType").append("<option value=''>请选择</option>"); ;
                $.each(orgTypes,function(i,obj){
                    $("#selectOrgType").append("<option value='"+obj.id+"'>"+obj.text+"</option>"); ;
                });
            }else{
                toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
            }
        }
    }

    function _showOrgList(pageNum){
        $("#orgListTb").empty();
        var pageInfo = {};
        pageInfo.pageNumber = pageNum;
        pageInfo.pageSize  = 20
        orgparam.pageInfo  = pageInfo;
        var result = client.callAsJson("userService/queryOrgarizationsByCond", orgparam);
        if (result.success) {
            if(result.result != null){
                $("#orgListTb").datagrid({
            	    nowrap:false,
            	    fitColumns:true,
                    columns : orgcolumns,
                    data : result.result
                });

                //TODO 显示分页
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
        
    };
	function _addOrUpdateInfo(type){

        $("#userInfoForm").bootstrapValidator('validate');//提交验证
        if (!$("#userInfoForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
            return;
        }
        var staffName = $("#staffName").val();
	    if(staffName == undefined || staffName == ''){
	        toastr.warning("请输入用户名称！！");
	        return;
        }
	    var staffCode = $("#staffCode").val();
        if(staffCode == undefined || staffCode == ''){
            toastr.warning("请输入登录账号！！");
            return;
        }
        var staffPwd = $("#passWord").val();
        if(operType == 'add'){

            if(staffPwd == undefined || staffPwd == ''){
                toastr.warning("请输入登录密码！！");
                return;
            }
        }

	    var mobileNum = $("#mobileNum").val();
        if(mobileNum == undefined || mobileNum == ''){
            toastr.warning("请输入手机号码！！");
            return;
        }
	    var linkTel = $("#linkTel").val();
	    var email = $('#email').val();
	    var orgId = $("#orgId").prop('orgId');
        //弹出组织框的时候设定了
        if(orgId == undefined || orgId == ''){
            toastr.warning("请选择组织单位！！");
            return;
        }

	    var paramStaff = {};
	    var staff = {}
	    staff.name = staffName;
	    staff.staffCode = staffCode;
	    if(operType == 'add'){
            staff.staffPwd = staffPwd;
        }
	    staff.mobilePhone = mobileNum;
	    staff.linkTel = linkTel;
	    staff.email = email;
	    staff.orgId = orgId;
	    staff.operType = operType;
        if(operType == 'modify' || operType == 'del'){
            staff.staffId = staffDto.staffId;
        }
	    paramStaff.staff = staff;
        var result = client.callAsJson("userService/saveOrUpdateStaff", paramStaff);
        if (result.success) {
            if(result.result != null){
                $('#userAddEditModal').modal('hide')
                toastr.info("操作成功！");
                _doSearchPage(1,param);
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }


    }
	function _doSearchPage(index,param){

        // var pageInfo={};
        // pageInfo.pageNumber = index;
        // pageInfo.pageSize =  15;
        // param.pageInfo = pageInfo;

        //初始化权限菜单
        var result = client.callAsJson("userService/queryStaffsByCond", param);
        if (result.success) {
            if(result.result != null){
                _showUserListUi(index,result.result);
            }
        } else {
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    }

    function _showUserListUi(idx,result){
        var columns=[[
            {field:'checkRow',title:"选择",width:100,fitColumns:true,checkbox : true  },
            {field:'staffId',title:'',fitColumns:true,hidden:true},
            {field:'staffCode',title:"登录账号",width:$(this).width()*0.06,fitColumns:true},
            {field:'staffPwd',title:"登录密码",width:$(this).width()*0.06,fitColumns:true},
            {field:'name',title:"用户名称",width:$(this).width()*0.05,fitColumns:true},
            {field:'mobilePhone',title:"手机号码",width:$(this).width()*0.07,fitColumns:true},
            {field:'linkTel',title:"联系电话",width:$(this).width()*0.1,fitColumns:true},
            {field:'email',title:"电子邮箱",width:$(this).width()*0.1,fitColumns:true},
            {field:'orgName',title:"单位",width:$(this).width()*0.1,fitColumns:true},
            {field:'statusCd',title:"状态Cd",fitColumns:true,hidden:true},
            {field:'statusName',title:"状态",width:$(this).width()*0.05,fitColumns:true},
            {field:'operation',title:"操作",width:$(this).width()*0.07,
                formatter: function(value,row,index){
                    return  '<a href="javascript:;"  onclick="com.im.userManage.invoke.modifyStaff(\''+index+'\',\'role\')" title="角色授予"><i class="fa fa-user"></i></a>'+
                            '<a href="javascript:;" onclick="com.im.userManage.invoke.modifyStaff(\''+index+'\',\'limit\')" title="数据授予"><i class="fa fa-key"></i></a>'+
                            '<a href="javascript:;" onclick="com.im.userManage.invoke.modifyStaff(\''+index+'\',\'modify\')" title="修改"><i class="fa fa-edit"></i></a>'
                          +' <!-- <a href="javascript:;" onclick="com.im.userManage.invoke.modifyStaff(\''+index+'\',\'del\')" title="删除"><i class="fa fa-trash"></i></a>-->';
                }},
        ]];

        $("#userInfoList").datagrid({
    	    nowrap:false,
    	    fitColumns:true,
            columns : columns,
            data : result.rows
        });

        //页码
        $("#page").pagination({
            total : result.total,
            pageSize : result.pageSize,
            pageNumber : result.pageNumber,
            pageList : [10,20,40],
            beforePageText:  '第' ,
            afterPageText: '页 共'+result.totalPages+'页',
            displayMsg: '共 '+result.total+'条记录',
            onSelectPage: function (pageNumber, pageSize) {
                param.pageInfo.pageNumber = pageNumber;
                param.pageInfo.pageSize = pageSize;
                _doSearchPage(pageNumber,param);
            }
        });
    };
	function _modifyStaff2Roles(index,operType){
        var role = $('#roleInfoList').datagrid('getData').rows[index];
        var staff2Role = {};
        staff2Role.operType = operType;
        staff2Role.roleId = role.roleId;
        staff2Role.staffId = staffDto.staffId;
        var oparam = {};
        oparam.staff2Role = staff2Role;
        var result = client.callAsJson("userService/saveOrUpdateStaff", oparam);
        if(result.success){
            if(operType == 'add'){
                //hasList添加
                hasList.push(staff2Role);
            }else{
                //haslist删除
                for(var i=0; i<hasList.length; i++){
                    if(hasList[i].roleId == staff2Role.roleId){
                        hasList.splice(i,1);
                        return false;
                    }
                }
            }
            //更新显示
            $("#roleInfoList").datagrid({
                columns : rolecolumns,
                data : allList
            });
        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    };

	function _modifyStaff(index,type){
        staffDto = $('#userInfoList').datagrid('getData').rows[index];
        if(type == 'modify'){
            //展示
            _showStaff(staffDto);
            operType = "modify";
            $("#myModalLabel12").html("修改用户");
            $("#userAddEditModal").modal('show');
        }
        if(type == 'del'){
            _showStaff(staffDto);
            operType = "del";
            $("#myModalLabel12").html("删除用户");
            $("#userAddEditModal").modal('show');
        }
        if(type == 'role'){
            $("#roleChoseModal").modal('show');
//            _showStaffRole(staffDto.staffId)
        }
        if(type == 'limit'){
            _showStafflimit(staffDto.staffId);
            $("#powerChoseModal").modal('show');
        }
    };
    function _showStaffRole(staffId){
        //查询员工的角色组
        var qparam = {};
        qparam.staffId =  staffId;
        qparam.staff2Roles = 'Y';
        //初始化权限菜单
        var result;
        //var hasList;//操作员工角色对象

        result = client.callAsJson("userService/queryStaffBaseInfo", qparam);
        if (result.success) {
            hasList = result.result.staff2Roles;
            _queryConfigRolesPage(hasList,1,10);
        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }


    };

    function _queryConfigRolesPage(hasList,idx,size){
        //查询配置的角色组
        var qparam = {};
        var pageInfo = {};
        pageInfo.pageNumber = idx;
        pageInfo.pageSize = size;
        qparam.statusCd = '10';
        qparam.pageInfo = pageInfo;

        result = client.callAsJson("userService/queryConfigRolesByCond", qparam);
        var allList = [];
        if (result.success) {
            allList = result.result.rows;
            //展示
            $("#roleInfoList").datagrid({
        	    nowrap:false,
        	    fitColumns:true,
                columns : rolecolumns,
                data : allList
            });
            //页码
            //页码
            $("#page3").pagination({
                total : result.result.total,
                pageSize : result.result.pageSize,
                pageNumber : result.result.pageNumber,
                pageList : [10,20,40],
                beforePageText:  '第' ,
                afterPageText: '页 共'+result.result.totalPages+'页',
                displayMsg: '共 '+result.result.total+'条记录',
                onSelectPage: function (pageNumber, pageSize) {
                    _queryConfigRolesPage(hasList,pageNumber,pageSize);
                }
            });
                // $('#page3').pagination({
                //     items: 11,
                //     itemsOnPage: 1,
                //     prevText: "上一页",
                //     nextText: "下一页",
                //     onPageClick: function (pageNumber, event){//当页面被点击时调用的函数。可选参数：页面数和事件。
                //         alert(pageNumber);
                //         _queryConfigRolesPage(pageNumber);
                //     },
                //     onInit: function (){//初始化调用的函数
                //
                //     }
                // });

        }else{
            toastr.error("服务器忙！请稍后再试！"+result.resultMsg);
        }
    };
	function _showStaff(staff){
	    if(operType == 'add'){
            $("#staffName").val('');
            $("#staffCode").val('');
            $("#staffPwd").val('')
            $("#pwdDiv").show();
            $("#mobileNum").val('');
            $("#linkTel").val('');
            $("#email").val('');
            //$("#orgId").val('');
            //$("#orgId").prop('orgId','');
            _initFormValid()
        }else{
            $("#staffName").val(staff.name);
            $("#staffCode").val(staff.staffCode);
            $("#staffPwd").val(staff.staffPwd)
            $("#pwdDiv").hide();
            $("#mobileNum").val(staff.mobilePhone);
            $("#linkTel").val(staff.linkTel);
            $("#email").val(staff.email);
            $("#orgId").val(staff.orgName);
            $("#orgId").prop('orgId',staff.orgId);
            _initFormValidMod();
        }


    };

	function _initFunc(){
        //树形菜单
//        $("#jobTree,#powerTree,#unitSearchTree").treeview({
//            animated: "fast",
//            collapsed: true,
//            unique: true,
//            persist: "cookie",
//            toggle: function() {
//
//            }
//        });

        //复选框
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass   : 'iradio_minimal-blue'
        });
        //下拉框
        $('.select2').select2();
    };
    //员工权限
    function _showStafflimit(staffId){
        //初始化员工权限类型下拉框
        _initStaffLimitType();

        //初始化当前员工权限
        _initStaffLimitLogined();

    };
    //员工维度实例数据
    function _initStaffLimit(pNum,pSize){

        var sId = staffDto.staffId;
        var staffLimitType = $("#staffLimitTypeSel").val();
        if(staffLimitType == null || staffLimitType == ''){
            $("#limitListTab").empty();
            $("#page4").empty();
            $("#limitSaveBtn").prop("disabled",true);
        }else{
            $("#limitSaveBtn").prop("disabled",false);
            var ifHasAll = false;
            //查询当前用户的所有维度
            if(entry["if_load_"+sId] && entry["if_all_limit_"+sId]){
                //是否加载过，是则判断是否通用权限，否则继续
                ifHasAll = true;
                //不需要查询了
                $("#checkAllInput").prop("checked",true);
                $("#staffLimitTypeSel").prop("disabled",true);
                //
                $("#limitListTab").empty();
                //
                $("#page4").empty();

            }else{
                if(!entry["if_load_"+sId+"_"+staffLimitType]){
                    //是否加载过某类权限
                    var result = client.callAsJson("userService/queryLimitInstByCond", {"staffId":sId,"stafflimitType":staffLimitType});
                    if(result.success){
                        if(result.ifHasAll == 'Y'){
                            ifHasAll = true;
                            entry["if_load_"+sId] = true;
                            entry["if_all_limit_"+sId] = true;
                        }else{
                            entry["if_load_"+sId] = true;
                            entry["if_all_limit_"+sId] = false;
                            entry["if_load_"+sId+"_"+staffLimitType+"_list"] =  result.result;
                        }

                    }else{
                        entry["if_load_"+sId] = false;
                        entry["if_all_limit_"+sId] = false;
                        entry["if_load_"+sId+"_"+staffLimitType+"_list"] =  [];
                    }
                }

                //查询实例维度
                var pageQuery = _searchList(staffLimitType,pNum,pSize);
                //展示实例维度
                if (pageQuery == '') {
                    $("#page4").empty();
                    $("#limitListTab").empty();
                } else {
                    _showList(pageQuery,staffLimitType);
                }


            }
        }
    }
    function _searchList(limitType,pNum,pSize){
        if(limitType == '10'){
            return _initProjects(pNum,pSize)
        }else if(limitType == '20'){
            return _initItems(pNum,pSize);
        }else if(limitType == '30'){
            return _initTenders(pNum,pSize);
        }else  if(limitType == '40'){
            return _initProcs(pNum,pSize);
        } else {
            return _initBusiConstParam(pNum,pSize,limitType);
        }
    }
    function _showList(pageQuery,limitType){
        var limitcolumns=[[
            {field:'checkedFlag',title:'',width:40,fitColumns:true,checkbox:true,singleSelect:false,
             formatter: function(value,row,index){
                return value;
             }
            },
            {field:'limitRangeId',title:'',width:40,fitColumns:true,hidden:true},
                // formatter: function(value,row,index){
                //     return  '<input type="checkbox" name="limit_chose_r" class="minimal" value='+index+'></input>';
                // }
                //},
            {field:'rowIndex',title:"序号",width:100,fitColumns:true,
             formatter: function(value,row,index){
                return (index+1);
             }},
            {field:'limitValue',title:"权限对象值",width:100,fitColumns:true,hidden:true},
            {field:'limitTypeId',title:"数据维度类型",width:100,fitColumns:true,
                formatter: function(value,row,index){
                    var v = '未定义';
                    $.each(staffLimitTypes,function (i,obj) {
                        if(value == obj.limitTypeId){
                            v = obj.limitTypeName;
                            return false;
                        }
                    })
                    return v;
                }},
            {field:'limitValueName',title:"权限对象",width:100,fitColumns:true},
            {field:'startDt',title:"权限生效时间",width:100,fitColumns:true,
                //时间插件
                // $('#startDatepicker').datepicker({
                //     onSelect:function (){
                //         $('#startDatepicker').trigger("change");
                //     }
                // });
                formatter: function(value,row,index){
                    return '<input type="text" class="c_datapicker form-control pull-right" value="'+value+'" id="datepicker_start_'+index+'"/>';
                }},
            {field:'endDt',title:"权限失效时间",width:100,fitColumns:true,
                formatter: function(value,row,index){
                    return '<input  type="text" class="c_datapicker form-control pull-right" value="'+ value +'" id="datepicker_end_'+index+'"/>';
            }},
            {field:'description',title:"描述",width:100,fitColumns:true}
        ]];

        $("#limitListTab").datagrid({
            nowrap:false,
            fitColumns:true,
            columns : limitcolumns,
            checkOnSelect : true,
            selectOnCheck : true,
            data : pageQuery.rows,
            onClickRow : function(idx){
                var isCheck = $('#limitListTab').datagrid("getPanel").find(".datagrid-view2 .datagrid-body table input[type='checkbox']:eq(" + idx + ") ").prop("checked");
                if(isCheck){
                    $('#limitListTab').datagrid("getPanel").find(".datagrid-view2 .datagrid-body table input[type='checkbox']:eq(" + idx + ") ").prop("checked", false);
                    $('#limitListTab').datagrid("checkRow",idx);
                }else{
                    $('#limitListTab').datagrid("getPanel").find(".datagrid-view2 .datagrid-body table input[type='checkbox']:eq(" + idx + ") ").prop("checked", true);
                    $('#limitListTab').datagrid("uncheckRow",idx);
                }
            },
            onLoadSuccess : function(){
                //选中
                $.each(pageQuery.rows,function(i,obj){
                    if(obj.checkedFlag){
                        $("#limitListTab").datagrid("selectRow", i);
                        $('#limitListTab').datagrid("getPanel").find(".datagrid-view2 .datagrid-body table input[type='checkbox']:eq(" + i + ") ").prop("checked",true);
                    }
                });
            }
        });

        //页码
        $("#page4").pagination({
            total : pageQuery.total,
            pageSize : pageQuery.pageSize,
            pageNumber : pageQuery.pageNumber,
            pageList : [10,20,40],
            beforePageText:  '第' ,
            afterPageText: '页 共'+pageQuery.totalPages+'页',
            displayMsg: '共 '+pageQuery.total+'条记录',
            onSelectPage: function (pageNumber, pageSize) {
                var pageQuery  = _searchList(limitType,pageNumber,pageSize);
                _showList(pageQuery,limitType);
            }
        });

        //事件
        $(".c_datapicker").datepicker({
            onSelect:function (){
                $(this).trigger("change");
            }
        });
    }
    function  _saveOrUpdateLimit(){
        var oparam = {};
        var dellist = [];
        var addlist = [];
        var modlist = [];

        var checkall = $("#checkAllInput").prop("checked");
        if(checkall){
            if(!ifHasAll){
                //原始没全选、现在全选
                var addobj = {};
                addobj.staffId = staffDto.staffId;
                addobj.limtiTypeId = '-9999';
                addlist.push(addobj);
            }
        }else{
            if(ifHasAll){
                //原来全选、现在没全选
                var delobj = {};
                addobj.staffId = staffDto.staffId;
                addobj.limtiTypeId = '-9999';
                dellist.push(addobj);
            }
            var nowlist = $("#limitListTab").datagrid('getChecked');
            if(nowlist == undefined){
                nowlist = [];
            }
            var limitType = $("#staffLimitTypeSel").val();

            //原始存在、现不存在
            $.each(entry["if_load_"+staffDto.staffId+"_"+limitType+"_list_page"],function (i,iobj) {
                if(iobj.checkedFlag){
                    //原存在
                    var ifexists = false;
                    $.each(nowlist,function (j,jobj) {
                        if(iobj.limitValue == jobj.limitValue){
                            ifexists = true;
                            return false;
                        }
                    });
                    if(!ifexists){
                        //现不存在
                        dellist.push(iobj);
                    }
                }
            });

            //原始不存在、现在存在
            $.each(nowlist,function (i,iobj) {

                var ifexists = false;
                $.each(entry["if_load_"+staffDto.staffId+"_"+limitType+"_list_page"],function(j,jobj) {
                    if(iobj.limitValue == jobj.limitValue && jobj.checkedFlag){
                        ifexists = true;
                        return false;
                    }
                });
                if(!ifexists){
                    addlist.push(iobj);
                }
            });

            //原始存在、现在存在、做对比
            $.each(entry["if_load_"+staffDto.staffId+"_"+limitType+"_list_page"],function (i,iobj) {
                if(iobj.checkedFlag){
                    //原存在
                    $.each(nowlist,function (j,jobj) {
                        if(iobj.limitValue == jobj.limitValue){
                            //现存在
                            if(iobj.startDt != jobj.startDt
                                || iobj.endDt != jobj.endDt ){
                                modlist.push(jobj);
                            }
                            return false;
                        }
                    });

                }
            });
        }


        if(dellist.length > 0
            || addlist.length > 0
            || modlist.length > 0
            ){
            oparam.checkall = "N";
            oparam.addlist = addlist;
            oparam.dellist = dellist;
            oparam.modlist = modlist;

            var result = client.callAsJson("userService/saveOrUpdateStaffLimit",oparam);
            if(result.success){
                delete entry["if_load_"+staffDto.staffId+"_"+limitType+"_list_page"];
                delete entry["if_load_"+staffDto.staffId+"_"+limitType+"_list"];
                delete entry["if_load_"+staffDto.staffId+"_"+limitType];
                delete entry["if_load_"+staffDto.staffId];
                $("#powerChoseModal").modal('hide');
                toastr.error('操作成功！');
            }else{
                toastr.error('服务器忙，赋权失败，'+result.resultMsg);
            }
        }else{
            $("#powerChoseModal").modal('hide');
        }
    }
    //规划类
    function _initProjects(pNum,pSize){
        var qparam = {pageInfo : {pageNumber:1,pageSize:20}};
        qparam.pageInfo.pageNumber = pNum;
        qparam.pageInfo.pageSize = pSize;
        qparam.sort = "start_dt";
        qparam.order = "desc";
        var result = client.callAsJson("projectInfoService/queryPlanProjList", qparam);
        if (result.success) {
            return _insortResult(result.result,pSize,pNum,'10');
        } else {
            toastr.error('项目查询失败'+result.resultMsg);
            return _insortResult(null,pSize,pNum,'10');;
        }
    }
    //实施类
    function _initItems(pNum,pSize){
        var qparam = {pageInfo : {pageNumber:1,pageSize:20}};
        qparam.pageInfo.pageNumber = pNum;
        qparam.pageInfo.pageSize = pSize;
        qparam.sort = "start_dt";
        qparam.order = "desc";
        var result = client.callAsJson("projectInfoService/queryImpleProjList", qparam);
        if (result.success) {
            return _insortResult(result.result,pSize,pNum,'20');
        } else {
            toastr.error('实施项目查询失败'+result.resultMsg);
            return _insortResult(null,pSize,pNum,'20');;
        }
    }
    //招标类
    function _initTenders(pNum,pSize){
        var qparam = {};
        qparam.pageNumber = pNum;
        qparam.pageSize = pSize;
        qparam.page = pNum;
        qparam.rows = pSize;
        qparam.projectId = "";
        qparam.planProjClass = "";
        qparam.docName = "";
        //: "", planProjClass: "", docName: "", page: 1, rows: 10}
        var result = client.callAsJson("tenderPreparationService/queryInviteInfo", qparam);
        if (result.success) {
            return _insortResult(result.result,pSize,pNum,'30');
        } else {
            toastr.error('项目查询失败'+result.resultMsg);
            return _insortResult(null,pSize,pNum,'30');;
        }
    }
    //合同类
    function _initProcs(pNum,pSize){
        var qparam = {};
        qparam.pageNumber = pNum;
        qparam.pageSize = pSize;
        qparam.impleProjName = "";
        qparam.orgName = "";
        qparam.orgId = "";
        qparam.page = pNum;
        //{pageNumber: 1, pageSize: 20, impleProjName: "", orgName: "", orgId: "", page: 1}
        var result = client.callAsJson("queryBusiConstList/queryContractList", qparam);
        if (result.success) {
            return _insortResult(result.result,pSize,pNum,'40');
        } else {
            toastr.error('项目查询失败'+result.resultMsg);
            return _insortResult(null,pSize,pNum,'40');;
        }
    }

    function _initBusiConstParam(pNum,pSize,limitType){
        var qparam = {};
        qparam.pageNumber = pNum;
        qparam.pageSize = pSize;
        if (limitType == '50') {
            qparam.constParamCode ='ONLINE_BROWE_DOC_TYPE';
        } else if (limitType == '60') {
            qparam.constParamCode  ='CHECK_LIMIT_TYPE';
        } else {
            qparam.constParamCode  ='';
        }
        qparam.page = pNum;
        var result = client.callAsJson("busiConstService/queryBusiConstList", qparam);
        if (result.success) {
            return _insortResult(result,pSize,pNum,limitType);
        } else {
            toastr.error('查询常量配置失败'+result.resultMsg);
            return _insortResult(null,pSize,pNum,limitType);
        }
    }

    function _insortResult(pageQuery,PNum,pSize,limitType){

        if(pageQuery == undefined || pageQuery == null){
            pageQuery = {};
            pageQuery.rows = [];
            pageQuery.total = 0;
            pageQuery.pageSize = pSize;
            pageQuery.pageNumber = PNum;
            pageQuery.totalPages = 0;
        }else{
            var rows = [];
            if (pageQuery.rows ==null && pageQuery.rows ==undefined) {
                $.each(pageQuery.result,function (i) {
                    var rowobj = {};
                    if(limitType == '10'){
                       ;
                    }else if(limitType == '20'){
                       ;
                    }else if(limitType == '30'){
                        ;
                    }else if(limitType == '40'){
                        ;
                    } else {
                        rowobj.limitValue = pageQuery.result[i].paramValId;
                        rowobj.limitValueName = pageQuery.result[i].paramValName;
                        rowobj.limitTypeId = limitType;
                    }
                    //起止时间
                    var ifExists = false;
                    $.each(entry["if_load_"+staffDto.staffId+"_"+limitType+"_list"],function (j,jobj) {
                        if(jobj.limitValue == rowobj.limitValue){
                            ifExists = true;
                            rowobj.startDt = jobj.startDt;
                            rowobj.endDt = jobj.endDt;
                            rowobj.limitRangeId = jobj.limitRangeId;
                            rowobj.checkedFlag = true;
                            return false;
                        }
                    });
                    if(!ifExists){
                        var myDate = new Date();

                        //获取当前年
                        var year = myDate.getFullYear();

                        //获取当前月
                        var month = myDate.getMonth() + 1;

                        //获取当前日
                        var date = myDate.getDate();
                        rowobj.startDt =  year + '-' + conver(month) + "-" + conver(date) ;
                        rowobj.endDt = '3000-01-01';
                        rowobj.limitRangeId = "-"+i;
                        rowobj.checkedFlag = false;
                    }
                    rowobj.staffId = staffDto.staffId;
                    rows.push(rowobj);
                });
            } else {
                $.each(pageQuery.rows,function (i,obj) {

                    var rowobj = {};
                    if(limitType == '10'){
                        rowobj.limitValue = obj.planProjId;
                        rowobj.limitValueName = obj.planProjName;
                        rowobj.limitTypeId = limitType;
                    }else if(limitType == '20'){
                        rowobj.limitValue = obj.impleProjId;
                        rowobj.limitValueName = obj.impleProjName;
                        rowobj.limitTypeId = limitType;
                    }else if(limitType == '30'){
                        rowobj.limitValue = obj.tenderInfo.tenderInfoId;
                        rowobj.limitValueName = obj.tenderInfo.tenderTitle;
                        rowobj.limitTypeId = limitType;
                    }else if(limitType == '40'){
                        rowobj.limitValue = obj.contractId;
                        rowobj.limitValueName = obj.contractName;
                        rowobj.limitTypeId = limitType;
                    } else {
                        rowobj.limitValue = obj.paramValId;
                        rowobj.limitValueName = obj.paramValName;
                        alert("obj.paramValId==="+obj.paramValId);
                        rowobj.limitTypeId = limitType;
                    }

                    //起止时间
                    var ifExists = false;
                    $.each(entry["if_load_"+staffDto.staffId+"_"+limitType+"_list"],function (j,jobj) {
                        if(jobj.limitValue == rowobj.limitValue){
                            ifExists = true;
                            rowobj.startDt = jobj.startDt;
                            rowobj.endDt = jobj.endDt;
                            rowobj.limitRangeId = jobj.limitRangeId;
                            rowobj.checkedFlag = true;
                            return false;
                        }
                    });
                    if(!ifExists){
                        var myDate = new Date();

                        //获取当前年
                        var year = myDate.getFullYear();

                        //获取当前月
                        var month = myDate.getMonth() + 1;

                        //获取当前日
                        var date = myDate.getDate();
                        rowobj.startDt =  year + '-' + conver(month) + "-" + conver(date) ;
                        rowobj.endDt = '3000-01-01';
                        rowobj.limitRangeId = "-"+i;
                        rowobj.checkedFlag = false;
                    }
                    rowobj.staffId = staffDto.staffId;
                    rows.push(rowobj);
                });
            }

            //元素数据记录
            entry["if_load_"+staffDto.staffId+"_"+limitType+"_list_page"] = rows;
            pageQuery.rows = rows;
        }
        return pageQuery;
    }

    function _initStaffLimitLogined(){
        var ifHasAll = false;
        if(!ifHasAllLogined){
            var result = client.callAsJson("userService/queryLimitInstByCond", {staffId : staffDto.staffId});
            if(result.success){
                if(result.ifHasAllLogined == 'Y'){
                    ifHasAllLogined = true;
                    if(result.ifHasAll == 'Y'){
                        ifHasAll = true;
                    }else{
                        ifHasAll = false;
                    }
                }else{
                    ifHasAllLogined = false;
                    ifHasAll = false;
                }
            }else{
                toastr.warning(result.resultMsg);
                $("#staffLimitTypeSel").prop("disabled",false);
                return;
            }
        }
        if(ifHasAllLogined){
            $("#checkAllDiv").empty();
            $("#checkAllDiv").append('<span><input id="checkAllInput" type="checkbox" class="minimal">通用数据维护(全部业务数据可视)</input></span>');
            $("#checkAllInput").click(function () {
                var c = $("#checkAllInput").prop("checked");
                if(c){
                    $("#staffLimitTypeSel").prop("disabled",true);
                    //
                    $("#limitListTab").datagrid({
                        nowrap:false,
                        fitColumns:true,
                        data : []
                    });

                    $("#page4").empty();
                }else{
                    $("#staffLimitTypeSel").prop("disabled",false);
                    $("#staffLimitTypeSel").val("");
                    $("#limitListTab").datagrid({
                        nowrap:false,
                        fitColumns:true,
                        data : []
                    });

                    $("#page4").empty();
                }
            });
            if(ifHasAll){
                $("#checkAllInput").prop("checked",true);
                $("#staffLimitTypeSel").prop("disabled",true);

            }else{
                $("#checkAllInput").prop("checked",false);
                $("#staffLimitTypeSel").prop("disabled",false);
            }
            $("#staffLimitTypeSel").val("");
            $("#limitListTab").datagrid({
                nowrap:false,
                fitColumns:true,
                data : []
            });

            $("#page4").empty();
        }else{
            $("#staffLimitTypeSel").val("");
            $("#staffLimitTypeSel").prop("disabled",false);
            $("#limitListTab").datagrid({
                nowrap:false,
                fitColumns:true,
                data : []
            });

            $("#page4").empty();
        }
    }

    //员工权限类型
    function _initStaffLimitType(){
        if(staffLimitTypes == undefined){
            var result = client.callAsJson("userService/queryConfigStaffLimitType", {});
            if(result.success){
                staffLimitTypes = result.result;
            }else{
                staffLimitTypes = [];
            }
            //初始化下拉框
            $("#staffLimitTypeSel").append('<option value="">请选择</option>');
            $.each(staffLimitTypes,function (i,obj) {
                $("#staffLimitTypeSel").append('<option value="'+obj.limitTypeId+'">'+obj.limitTypeName+'</option>');
            });

            //事件
            $("#staffLimitTypeSel").change(function () {
                _initStaffLimit(1,20);
            });
        }else{
            $("#staffLimitTypeSel").val("");
            $("#limitListTab").datagrid({
                nowrap:false,
                fitColumns:true,
                data : []
            });

            $("#page4").empty();
        }
    };
    //日期时间处理
    function conver(s) {
        return s < 10 ? '0' + s : s;
    }
    function _batchUpdateStaff(type){
        var nowlist = $("#userInfoList").datagrid('getChecked');
        if(nowlist != undefined && nowlist.length > 0){
            var msgStr = "确认批量失效"+nowlist.length+"个用户么？";
            if(statusCd == '20'){
                type = "batcheff";
                var msgStr = "确认批量生效"+nowlist.length+"个用户么？";
            }
            com.im.common.confirm(msgStr,{},function(){
                var staffList = [];
                $.each(nowlist,function (i,obj) {
                    staffList.push(obj.staffId);
                });
                var result = client.callAsJson("userService/saveOrUpdateStaff", {staffList : staffList,batchOperType : type});
                if(result.success){
                    toastr.info("操作成功！");
                    _doSearchPage(1,param);
                }else{
                    toastr.error("服务器忙，请稍后再试！"+result.resultMsg);
                }
            });
        }
    }
    return {
		init : _init,
        modifyStaff : _modifyStaff,
        modifyStaff2Roles : _modifyStaff2Roles
	}
}();

$(function() {
	com.im.userManage.invoke.init();
});